﻿package 
{
	import flash.events.Event;
	import flash.display.MovieClip;
	
	public class BattlePlayer extends MovieClip 
	{
		public var Stats:BaseStats;
		private var ActionFrames:int;
		private var xDistance:Number;
		private var yDistance:Number;
		
		public function BattlePlayer(baseStats:BaseStats) 
		{
			addEventListener(Event.ENTER_FRAME, EnterFrame);
			addEventListener(Event.REMOVED, Unload);
			Stats = baseStats;
			init();
		}
		
		private function init():void
		{
			ActionFrames = 0;
			holdFrame();
			if (body != null)
			{
				body.stop();
			}
			rarm.LoadWeapon();
		}
		
		private function holdFrame():void
		{
			if (body != null)
			{
				if (body.larm != null)
				{
					body.larm.gotoAndStop(Stats.FrameNum);
				}
				if (body.rarm != null)
				{
					body.rarm.gotoAndStop(Stats.FrameNum);
				}
				if (body.rleg != null)
				{
					body.rleg.gotoAndStop(Stats.FrameNum);
				}
				if (body.lleg != null)
				{
					body.lleg.gotoAndStop(Stats.FrameNum);
				}
				if (body.body != null)
				{
					body.body.gotoAndStop(Stats.FrameNum);
				}
				if (body.head != null)
				{
					body.head.gotoAndStop(Stats.FrameNum);
				}
			}
		}
		
		public function ExecuteAttack(target:MovieClip):void
		{
			xDistance = (Math.abs(this.parent.x - target.x + target.width + 10) / (Constants.AnimationLength / 3));
			yDistance = (Math.abs(this.parent.y - target.y) / (Constants.AnimationLength / 3));
			trace(rarm.rotation);
			
			if (target.y < this.parent.y)
			{
				yDistance = (yDistance * -1)
			}
			if (target.x < this.parent.x)
			{
				xDistance = (xDistance * -1)
			}
			
			ActionFrames = Constants.AnimationLength;
		}
		
		private function EnterFrame(event:Event):void
		{
			var animationDivisor:int = (Constants.AnimationLength / 3);
			if (ActionFrames <= Constants.AnimationLength && ActionFrames > (animationDivisor * 2))
			{
				rarm.rotation -= 10;
				this.x += xDistance;
				this.y += yDistance;
			}
			else if (ActionFrames <= (animationDivisor * 2) && ActionFrames > animationDivisor)
			{
				rarm.rotation += 20;
			}
			else if (ActionFrames <= animationDivisor && ActionFrames > 0)
			{
				rarm.rotation -= 10;
				this.x -= xDistance;
				this.y -= yDistance;
			}
			if (ActionFrames > 0)
			{
				ActionFrames--;
			}
			else
			{
				this.x = 0;
				this.y = 0;
			}
		}
		
		private function Unload(event:Event):void
		{
			if (event.target.name == this.name)
			{
				removeEventListener(Event.ENTER_FRAME, EnterFrame);
			}
		}
		
	}
}